import apicon from './apicon.js'
import apis from './api.js'
import Vue from 'vue'
// 获取php后台的系统参数 比如当时时间
const getSysInfoApi = function() {
	return new Promise(function(result) {
		uni.request({
			url: apicon.host + apis.api.getSysInfoApi,
			data: {},
			method: "GET",
			header: {
				'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
				'token': uni.getStorageSync('localtokn') ? uni.getStorageSync('localtokn') : ''
			},
			success: function(data) {
				if (data.data.code == 1) {
					return result(data.data.data);
				}
			},
			error: function(data) {
				// 错误信息打印
				console.log(data)
			}
		});
	})
}

// 获取商户信息接口封装(常用)
var shopIndexApiFun = function() {
	return new Promise(function(result) {
		uni.request({
			url: apicon.host + apis.api.shopIndexApi,
			data: {},
			method: "GET",
			header: {
				'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
				'token': uni.getStorageSync('localtokn') ? uni.getStorageSync('localtokn') : ''
			},
			success: function(data) {
				if (data.data.code == 1) {
					return result(data.data.data);
				}
			},
			error: function(data) {
				// 商户错误信息打印
				console.log(data)
			}
		});
	})
}

// 获取经纬度及城市信息
const getLocation = function() {
	return new Promise(function(result, reject) {
		uni.getLocation({
			type: 'wgs84',
			geocode: true, //设置该参数为true可直接获取经纬度及城市信息
			success: function(res) {
				// console.log('当前位置的经度：' + res.longitude);
				// console.log('当前位置的纬度：' + res.latitude);
				return result(res)
			},
			fail: function(err) {
				console.log(err)
			}
		});
	})

}

//登录后操作
var goLogin = function() {
	if (!uni.getStorageSync('localtokn') && !uni.getStorageSync('temporaryUserInfo')) {
		uni.showToast({
			icon: 'none',
			title: '请登录后操作!'
		});
		// #ifndef MP-WEIXIN
		setTimeout(() => {
			uni.navigateTo({
				url: '/pages_Personalcenter/Signblock/uni_Login'
			});
		}, 1000)
		// #endif
		return true;
	}
}
//时间戳转化为日期
var GetTime = function(timestamp) {
	let times;
	//时间戳为10位需*1000转换为毫秒，时间戳为13位的话不需乘1000
	if (timestamp && (timestamp.toString()).length == 10) {
		times = Number(timestamp) * 1000
	} else {
		times = timestamp
	}
	let date = new Date(times ? Number(times) : (new Date().getTime()));

	let Y = date.getFullYear() + '-';

	let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';

	let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';

	let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';

	let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';

	let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();

	return Y + M + D + h + m + s;
}
// 返回上一页
const navigateBack = function(msg, url) {
	uni.showToast({
		title: msg,
		icon: 'none'
	})
	setTimeout(() => {
		if (url) {
			uni.reLaunch({
				url: url
			})
		} else {
			uni.navigateBack(uni.$emit("handleFun", '1'))
		}
	}, 1500)
}

// 手机号正则验证
const regPhone = /^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9]))\d{8}$/
// 身份证号验证
const regCard = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
// 邮箱正则验证
const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/
const regIdCard = function(id) {
	var city = {
		11: "北京",
		12: "天津",
		13: "河北",
		14: "山西",
		15: "内蒙古",
		21: "辽宁",
		22: "吉林",
		23: "黑龙江",
		31: "上海",
		32: "江苏",
		33: "浙江",
		34: "安徽",
		35: "福建",
		36: "江西",
		37: "山东",
		41: "河南",
		42: "湖北",
		43: "湖南",
		44: "广东",
		45: "广西",
		46: "海南",
		50: "重庆",
		51: "四川",
		52: "贵州",
		53: "云南",
		54: "西藏",
		61: "陕西",
		62: "甘肃",
		63: "甘肃",
		64: "浙江",
		65: "石家庄",
		71: "台湾",
		81: "香港",
		82: "澳门",
		91: "国外"
	};
	var reg = /^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/;
	if (reg.test(id)) {
		if (city[id.substr(0, 2)]) {
			// 城市码校验通过
			// 身份证的第18位校验码验证
			var sum = 0,
				idx;
			for (var i = 0; i < 17; i++) {
				sum += ((id.charAt(17) - '0') % 10) * (Math.pow(2, (18 - i)) % 11);
			}
			idx = sum % 11;
			var checkCode = '10X98765432';
			// if (checkCode.charAt(idx) != id.charAt(17)) {
			//     return false; // 校验码错误
			// }
			return true; // 身份证号码校验通过
		} else {
			return false; // 城市码不存在
		}
	} else {
		return false; // 身份证号码格式错误
	}
}
// 封装压缩图片方法(仅适用于h5)
function compressed(Paths) {
	var imgCompressed = new Promise(function(resolves, rejects) {
		uni.getImageInfo({
			src: Paths,
			success: function(image) {
				let canvasWidth = image.width //图片原始长宽
				let canvasHeight = image.height;
				let base = canvasWidth / canvasHeight;
				/* debugger */
				if (canvasWidth > 800) {
					canvasWidth = 800;
					canvasHeight = Math.floor(canvasWidth / base);
				}
				let img = document.createElement('img');
				img.src = Paths; // 要压缩的图片  
				let canvas = document.createElement('canvas');
				let ctx = canvas.getContext('2d');
				canvas.width = canvasWidth;
				canvas.height = canvasHeight;
				ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight);
				canvas.toBlob(function(fileSrc) {
					let imgSrc = window.URL.createObjectURL(fileSrc); //原生JS生成文件路径
					// 画布base64转图片
					var image = new Image();
					image.src = canvas.toDataURL("image/png");
					resolves(image.src)
				})
			}
		})
	})
	return imgCompressed
};

/**
 * 上传图片封装
 * chooseImage请求--携带token
 * @param {Object} url 请求链接
 * @param {Object} resolve 成功回调函数
 * @param {Object} reject 失败回调函数
 */
const uploadimg = function(num) {
	var num = num ? num : 1
	var arr = []
	var upload = new Promise(function(resolve, reject) {
		uni.chooseImage({
			count: num, //默认9
			sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
			success: (chooseImageRes) => {
				const tempFilePaths = chooseImageRes.tempFilePaths;
				// H5压缩图片后在进行上传图片
				for (let i = 0; i <= tempFilePaths.length; i++) {
					// #ifdef H5
					compressed(tempFilePaths[i]).then((imgCompressed) => {
						uni.showLoading({
							title: '正在上传'
						})
						uni.uploadFile({
							url: apicon.host + apis.api
								.uploadApi, //仅为示例，非真实的接口地址
							filePath: imgCompressed,
							sourceType: ['album'], //从相册选择
							name: 'file',
							header: {
								Authorization: uni.getStorageSync(
									'localtokn')
							},
							success: (uploadFileRes) => {
								if (JSON.parse(uploadFileRes.data).code ==
									1) {
									if (tempFilePaths.length >= 0) {
										uni.hideLoading()
										arr.push(JSON.parse(uploadFileRes
											.data).body)
										if (tempFilePaths.length - 1 == i) {
											resolve(arr)
										}
									} else {
										resolve(uploadFileRes.data.body)
									}
								} else {
									uni.showToast({
										icon: 'none',
										title: JSON.parse(
												uploadFileRes.data)
											.codeName
									})
								}
							},
						});
					})
					// #endif
					// app小程序压缩图片后上传
					// #ifndef H5
					// uni.compressImage({  
					//   src:tempFilePaths[0],  
					//   quality: 80, 
					//   success: res => {  
					uni.showLoading({
						title: '正在上传'
					})
					uni.uploadFile({
						url: apicon.host + apis.api.uploadApi, //仅为示例，非真实的接口地址
						// filePath: res.tempFilePath,
						filePath: tempFilePaths[i],
						sourceType: ['album'], //从相册选择
						name: 'file',
						header: {
							Authorization: uni.getStorageSync('localtokn')
						},
						success: (uploadFileRes) => {
							if (JSON.parse(uploadFileRes.data).code ==
								1) {
								if (tempFilePaths.length >= 0) {
									uni.hideLoading()
									arr.push(JSON.parse(uploadFileRes
										.data).body)
									if (tempFilePaths.length - 1 == i) {
										resolve(arr)
									}
								} else {
									resolve(uploadFileRes.data.body)
								}
							} else {
								uni.showToast({
									icon: 'none',
									title: JSON.parse(
											uploadFileRes.data)
										.codeName
								})
							}
						},
					});
					//   },  
					//   fail: (e) => {
					// 	console.log(e)  
					//   }
					// }) 
					// #endif
				}
			}
		});
	});
	return upload;
}

// 上传视频封装
const uploadVideo = function(num) {
	var upload = new Promise(function(resolve, reject) {
		var that = this;
		uni.chooseVideo({
			count: 1,
			camera: 'front',
			sourceType: ['camera', 'album'],
			success: function(res) {
				console.log("选择视频成功", res)
				uni.uploadFile({
					url: apicon.host + apis.api.uploadApi, //接口地址
					filePath: res.tempFilePath,
					name: 'file',
					// formData: {
					//     'user': 'test'
					// },
					header: {
						token: uni.getStorageSync('localtokn')
					},
					success: (uploadFileRes) => {
						console.log('1张', uploadFileRes);
						let bold = JSON.parse(uploadFileRes.data)
						console.log('bold', bold)
						// var returnImage = bold.result[0].filePath + bold.result[0].fileName
						// console.log("this.returnImage", returnImage)
						resolve(bold.data.url)
					},
					error: function(data) {
						uni.showToast({
							icon: 'none',
							title: data.data.msg
						});
					}
				});
			}
		});
	})
	return upload
}
const urlTobase64 = function(url) {
	return new Promise((resove, reject) => {
		uni.getFileSystemManager().readFile({
			filePath: url, //选择图片返回的相对路径
			encoding: 'base64', //编码格式
			success: res => { //成功的回调
				console.log(res);
				let base64 = 'data:image/jpeg;base64,' + res.data //不加上这串字符，在页面无法显示的哦

			},
			fail: (e) => {}
		})
	})
}
// 用户登录状态
var login_status = function() {
	if (!uni.getStorageSync('localtokn') && !uni.getStorageSync('temporaryUserInfo')) {
		return 0; //未登录
	} else if (uni.getStorageSync('temporaryUserInfo') && !uni.getStorageSync('localtokn')) {
		return 1; //微信登录,未绑定手机号
	} else {
		return 2; //正式登录
	}
}
const goBack = function() {
	uni.navigateBack()
}
const payFun = function(data) {
	return new Promise((resove, reject) => {
		uni.requestPayment({
			provider: 'wxpay', //支付方式简写
			// data,
			appId: data.wxAppId, //小程序Appid
			timeStamp: data.wxTimeStamp, //创建订单时间戳
			nonceStr: data.wxNonceStr,
			package: data.wxPackage, // 订单包
			signType: data.wxSignType, // 加密方式统一'MD5'
			paySign: data.wxPaySign, // 后台支付签名返回
			success: function(res) {
				console.log('success:' + JSON.stringify(res));
				resove(res)
			},
			fail: function(err) {
				console.log('fail:' + JSON.stringify(err));
				uni.showToast({
					title: '支付失败',
					icon: 'none'
				})
				reject(err)
			}
		});
	})
}

/*
*公共复制剪切板方法
* data.this 页面传递回过来的 vue实例
* data.title 需要复值的文本
* */ 
const copy = function(data){
	// #ifdef H5
	// data.this.$copyText(data.title).then(
	// 	res => {
	// 		uni.showToast({
	// 			title: data.msg||'复制成功',
	// 			icon: 'none',
	// 			duration:data.msg?5000:3000
	// 		})
	// 	}
	// )
	// #endif
	// #ifndef H5 
	 uni.setClipboardData({
	        data:data.title,//要被复制的内容
	        success:()=>{//复制成功的回调函数
	          uni.showToast({//提示
	            title:data.msg||'复制成功',
				icon: 'none',
				duration:data.msg?5000:3000
	          })
	        }
	      });
	// #endif
}
export default {
	getSysInfoApi, //获取系统信息
	getLocation, //获取经纬度
	shopIndexApiFun, //获取商户信息接口封装(常用)
	goLogin, //用户登录后在进行操作
	GetTime, //时间转化器
	navigateBack, //返回上一页封装
	regPhone, //手机号的正则验证封装
	emailRegex,//邮箱正则验证
	regIdCard, //身份证号的验证
	uploadimg, //上传图片的接口封装
	uploadVideo, //上传视频封装
	urlTobase64, //小程序背景图 默认转base64
	login_status, //0未登录;1微信已登录但未绑定手机号; 2正式登录以获取到tokengoBack，
	payFun, //支付接口
	goBack, //返回上一页
	copy,
}